<template>
  <PageContainer title="内容管理">
    <!-- 搜索筛选区域 -->
    <SearchForm v-model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-form-item label="内容筛选">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入标题或内容关键词"
          clearable
        />
      </el-form-item>
      <el-form-item label="内容类型">
        <el-select
          v-model="searchForm.type"
          placeholder="请选择内容类型"
          clearable
        >
          <el-option label="公告通知" value="announcement" />
          <el-option label="新闻资讯" value="news" />
          <el-option label="帮助文档" value="help" />
          <el-option label="活动信息" value="activity" />
          <el-option label="政策法规" value="policy" />
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态">
        <el-select
          v-model="searchForm.status"
          placeholder="请选择发布状态"
          clearable
        >
          <el-option label="已发布" value="published" />
          <el-option label="草稿" value="draft" />
          <el-option label="已下线" value="offline" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人员">
        <el-select
          v-model="searchForm.authorId"
          placeholder="请选择创建人员"
          clearable
          filterable
        >
          <el-option
            v-for="author in authorOptions"
            :key="author.id"
            :label="author.name"
            :value="author.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </SearchForm>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <StatCard
        :icon="Document"
        icon-bg="#409EFF"
        :value="contentStats.totalContent"
        label="总内容数"
        :trend="contentStats.totalTrend"
      />
      <StatCard
        :icon="CircleCheck"
        icon-bg="#67C23A"
        :value="contentStats.publishedContent"
        label="已发布内容"
        :trend="contentStats.publishedTrend"
      />
      <StatCard
        :icon="EditPen"
        icon-bg="#E6A23C"
        :value="contentStats.draftContent"
        label="草稿内容"
        :trend="contentStats.draftTrend"
      />
      <StatCard
        :icon="View"
        icon-bg="#909399"
        :value="contentStats.totalViews"
        label="总浏览量"
        :trend="contentStats.viewsTrend"
      />
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button
          type="primary"
          @click="handleCreateContent"
        >
          <el-icon><Plus /></el-icon>
          新建内容
        </el-button>
        <el-button
          type="success"
          :disabled="!selectedRows.length"
          @click="handleBatchPublish"
        >
          <el-icon><Upload /></el-icon>
          批量发布
        </el-button>
        <el-button
          type="warning"
          :disabled="!selectedRows.length"
          @click="handleBatchOffline"
        >
          <el-icon><Download /></el-icon>
          批量下线
        </el-button>
        <el-button
          type="danger"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
      <div class="action-right">
        <el-button
          type="info"
          @click="loadContentList"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 内容列表表格 -->
    <DataTable
      :data="contentList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="内容ID" width="80" />
      <el-table-column label="内容信息" min-width="300">
        <template #default="{ row }">
          <div class="content-info">
            <div class="content-title">
              <el-link type="primary" @click="handleViewDetail(row)">
                {{ row.title }}
              </el-link>
              <el-tag
                v-if="row.isTop"
                type="danger"
                size="small"
                style="margin-left: 8px"
              >
                置顶
              </el-tag>
              <el-tag
                v-if="row.isHot"
                type="warning"
                size="small"
                style="margin-left: 4px"
              >
                热门
              </el-tag>
            </div>
            <div class="content-summary">{{ row.summary }}</div>
            <div class="content-meta">
              <span>作者：{{ row.authorName }}</span>
              <span style="margin-left: 16px">浏览：{{ row.viewCount }}</span>
              <span style="margin-left: 16px">点赞：{{ row.likeCount }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="内容类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTypeTag(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" width="120">
        <template #default="{ row }">
          <el-image
            v-if="row.coverImage"
            :src="row.coverImage"
            fit="cover"
            style="width: 80px; height: 60px; border-radius: 4px;"
            :preview-src-list="[row.coverImage]"
          />
          <span v-else class="text-muted">无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="180" sortable>
        <template #default="{ row }">
          {{ row.publishedAt ? formatDateTime(row.publishedAt) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" sortable>
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.status === 'draft'"
            type="success"
            size="small"
            @click="handlePublish(row)"
          >
            发布
          </el-button>
          <el-dropdown @command="(command: string) => handleMoreAction(command, row)">
            <el-button type="text" size="small">
              更多<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="preview">预览</el-dropdown-item>
                <el-dropdown-item command="copy">复制</el-dropdown-item>
                <el-dropdown-item 
                  command="set-top" 
                  :disabled="row.isTop"
                >
                  {{ row.isTop ? '已置顶' : '设为置顶' }}
                </el-dropdown-item>
                <el-dropdown-item 
                  command="cancel-top" 
                  :disabled="!row.isTop"
                >
                  取消置顶
                </el-dropdown-item>
                <el-dropdown-item 
                  command="set-hot" 
                  :disabled="row.isHot"
                >
                  {{ row.isHot ? '已热门' : '设为热门' }}
                </el-dropdown-item>
                <el-dropdown-item 
                  command="offline" 
                  :disabled="row.status !== 'published'"
                  divided
                >
                  下线内容
                </el-dropdown-item>
                <el-dropdown-item command="delete">删除内容</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 内容详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="内容详情"
      width="80%"
    >
      <div v-if="currentContent" class="content-detail">
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="content-main">
              <h2 class="content-title">{{ currentContent.title }}</h2>
              <div class="content-meta">
                <el-tag :type="getTypeTag(currentContent.type)">
                  {{ getTypeText(currentContent.type) }}
                </el-tag>
                <el-tag :type="getStatusTag(currentContent.status)" style="margin-left: 8px">
                  {{ getStatusText(currentContent.status) }}
                </el-tag>
                <span style="margin-left: 16px; color: #909399;">
                  作者：{{ currentContent.authorName }}
                </span>
                <span style="margin-left: 16px; color: #909399;">
                  发布时间：{{ currentContent.publishedAt ? formatDateTime(currentContent.publishedAt) : '未发布' }}
                </span>
              </div>
              <div class="content-summary">
                <strong>摘要：</strong>{{ currentContent.summary }}
              </div>
              <div class="content-body" v-html="currentContent.content"></div>
            </div>
          </el-col>
          <el-col :span="8">
            <el-card title="内容信息">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="内容ID">
                  {{ currentContent.id }}
                </el-descriptions-item>
                <el-descriptions-item label="浏览量">
                  {{ currentContent.viewCount }}
                </el-descriptions-item>
                <el-descriptions-item label="点赞数">
                  {{ currentContent.likeCount }}
                </el-descriptions-item>
                <el-descriptions-item label="评论数">
                  {{ currentContent.commentCount }}
                </el-descriptions-item>
                <el-descriptions-item label="分享数">
                  {{ currentContent.shareCount }}
                </el-descriptions-item>
                <el-descriptions-item label="是否置顶">
                  <el-tag :type="currentContent.isTop ? 'success' : 'info'" size="small">
                    {{ currentContent.isTop ? '是' : '否' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="是否热门">
                  <el-tag :type="currentContent.isHot ? 'warning' : 'info'" size="small">
                    {{ currentContent.isHot ? '是' : '否' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ formatDateTime(currentContent.createdAt) }}
                </el-descriptions-item>
                <el-descriptions-item label="更新时间">
                  {{ formatDateTime(currentContent.updatedAt) }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>

            <!-- 封面图片 -->
            <el-card title="封面图片" style="margin-top: 16px;">
              <el-image
                v-if="currentContent.coverImage"
                :src="currentContent.coverImage"
                fit="cover"
                style="width: 100%; height: 200px;"
                :preview-src-list="[currentContent.coverImage]"
              />
              <div v-else class="no-cover">
                <el-icon><Picture /></el-icon>
                <span>暂无封面图片</span>
              </div>
            </el-card>

            <!-- 标签 -->
            <el-card title="内容标签" style="margin-top: 16px;">
              <div class="content-tags">
                <el-tag
                  v-for="tag in currentContent.tags"
                  :key="tag"
                  size="small"
                  style="margin-right: 8px; margin-bottom: 8px;"
                >
                  {{ tag }}
                </el-tag>
                <span v-if="!currentContent.tags?.length" class="text-muted">暂无标签</span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 新建/编辑内容对话框 -->
    <el-dialog
      v-model="contentDialogVisible"
      :title="isEdit ? '编辑内容' : '新建内容'"
      width="90%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="contentFormRef"
        :model="contentForm"
        :rules="contentRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="内容标题" prop="title">
              <el-input
                v-model="contentForm.title"
                placeholder="请输入内容标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="内容摘要" prop="summary">
              <el-input
                v-model="contentForm.summary"
                type="textarea"
                :rows="3"
                placeholder="请输入内容摘要"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="内容正文" prop="content">
              <div class="editor-container">
                <el-input
                  v-model="contentForm.content"
                  type="textarea"
                  :rows="15"
                  placeholder="请输入内容正文（支持HTML格式）"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内容类型" prop="type">
              <el-select
                v-model="contentForm.type"
                placeholder="请选择内容类型"
                style="width: 100%"
              >
                <el-option label="公告通知" value="announcement" />
                <el-option label="新闻资讯" value="news" />
                <el-option label="帮助文档" value="help" />
                <el-option label="活动信息" value="activity" />
                <el-option label="政策法规" value="policy" />
              </el-select>
            </el-form-item>
            <el-form-item label="发布状态" prop="status">
              <el-radio-group v-model="contentForm.status">
                <el-radio label="draft">保存为草稿</el-radio>
                <el-radio label="published">立即发布</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="封面图片">
              <el-upload
                class="cover-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeCoverUpload"
                :http-request="handleCoverUpload"
              >
                <el-image
                  v-if="contentForm.coverImage"
                  :src="contentForm.coverImage"
                  fit="cover"
                  style="width: 200px; height: 150px;"
                />
                <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="内容标签">
              <div class="tag-input">
                <el-tag
                  v-for="tag in contentForm.tags"
                  :key="tag"
                  closable
                  @close="removeTag(tag)"
                  style="margin-right: 8px; margin-bottom: 8px;"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="tagInputVisible"
                  ref="tagInputRef"
                  v-model="tagInputValue"
                  size="small"
                  style="width: 100px;"
                  @keyup.enter="handleTagInputConfirm"
                  @blur="handleTagInputConfirm"
                />
                <el-button
                  v-else
                  size="small"
                  @click="showTagInput"
                >
                  + 添加标签
                </el-button>
              </div>
            </el-form-item>
            <el-form-item label="特殊设置">
              <el-checkbox v-model="contentForm.isTop">置顶显示</el-checkbox>
              <el-checkbox v-model="contentForm.isHot" style="margin-left: 16px;">热门推荐</el-checkbox>
            </el-form-item>
            <el-form-item label="发布时间" v-if="contentForm.status === 'published'">
              <el-date-picker
                v-model="contentForm.publishedAt"
                type="datetime"
                placeholder="请选择发布时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="contentDialogVisible = false">取消</el-button>
        <el-button @click="handleSaveDraft" :loading="submitting">保存草稿</el-button>
        <el-button type="primary" @click="handleContentSubmit" :loading="submitting">
          {{ contentForm.status === 'published' ? '发布' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus'
import {
  Document,
  CircleCheck,
  EditPen,
  View,
  Plus,
  Upload,
  Download,
  Delete,
  Refresh,
  ArrowDown,
  Picture
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import SearchForm from '@/components/SearchForm.vue'
import DataTable from '@/components/DataTable.vue'
import StatCard from '@/components/StatCard.vue'
import { useContentStore } from '@/stores/content'
import { formatDateTime } from '@/utils'

const contentStore = useContentStore()

const loading = ref(false)
const submitting = ref(false)
const detailDialogVisible = ref(false)
const contentDialogVisible = ref(false)
const isEdit = ref(false)
const currentContent = ref<any>(null)
const selectedRows = ref<any[]>([])
const contentFormRef = ref<FormInstance>()
const tagInputRef = ref()
const tagInputVisible = ref(false)
const tagInputValue = ref('')

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: '',
  authorId: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 内容统计
const contentStats = reactive({
  totalContent: '1,256',
  totalTrend: '+12.5%',
  publishedContent: '1,089',
  publishedTrend: '+15.8%',
  draftContent: '167',
  draftTrend: '+8.2%',
  totalViews: '89,560',
  viewsTrend: '+22.1%'
})

// 内容列表
const contentList = ref<any[]>([])

// 作者选项
const authorOptions = ref<any[]>([
  { id: 1, name: '管理员' },
  { id: 2, name: '编辑员' },
  { id: 3, name: '运营员' }
])

// 内容表单
const contentForm = reactive({
  title: '',
  summary: '',
  content: '',
  type: 'announcement',
  status: 'draft',
  coverImage: '',
  tags: [] as string[],
  isTop: false,
  isHot: false,
  publishedAt: ''
})

// 表单验证规则
const contentRules: FormRules = {
  title: [
    { required: true, message: '请输入内容标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入内容摘要', trigger: 'blur' },
    { min: 10, max: 200, message: '摘要长度在 10 到 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容正文', trigger: 'blur' },
    { min: 50, message: '正文内容不能少于 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择内容类型', trigger: 'change' }
  ]
}

// 获取内容类型标签
const getTypeTag = (type: string) => {
  switch (type) {
    case 'announcement':
      return 'danger'
    case 'news':
      return 'primary'
    case 'help':
      return 'success'
    case 'activity':
      return 'warning'
    case 'policy':
      return 'info'
    default:
      return 'info'
  }
}

// 获取内容类型文本
const getTypeText = (type: string) => {
  switch (type) {
    case 'announcement':
      return '公告通知'
    case 'news':
      return '新闻资讯'
    case 'help':
      return '帮助文档'
    case 'activity':
      return '活动信息'
    case 'policy':
      return '政策法规'
    default:
      return '未知类型'
  }
}

// 获取状态标签
const getStatusTag = (status: string) => {
  switch (status) {
    case 'published':
      return 'success'
    case 'draft':
      return 'warning'
    case 'offline':
      return 'info'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'published':
      return '已发布'
    case 'draft':
      return '草稿'
    case 'offline':
      return '已下线'
    default:
      return '未知状态'
  }
}

// 加载内容列表
const loadContentList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    const response = await contentStore.fetchContentList(params)
    contentList.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载内容列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadContentList()
}

// 重置处理
const handleReset = () => {
  pagination.page = 1
  loadContentList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadContentList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadContentList()
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 新建内容
const handleCreateContent = () => {
  isEdit.value = false
  Object.assign(contentForm, {
    title: '',
    summary: '',
    content: '',
    type: 'announcement',
    status: 'draft',
    coverImage: '',
    tags: [],
    isTop: false,
    isHot: false,
    publishedAt: ''
  })
  contentDialogVisible.value = true
}

// 编辑内容
const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(contentForm, {
    ...row,
    tags: row.tags || []
  })
  contentDialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row: any) => {
  // 模拟获取内容详细信息
  currentContent.value = {
    ...row,
    content: `
      <p>这是一段示例内容正文。在实际应用中，这里会显示完整的文章内容。</p>
      <p>内容可以包含各种HTML标签，如<strong>粗体</strong>、<em>斜体</em>等格式。</p>
      <p>还可以包含图片、链接等多媒体元素。</p>
    `,
    viewCount: 1250,
    likeCount: 89,
    commentCount: 23,
    shareCount: 15,
    tags: ['环保', '回收', '智能设备']
  }
  detailDialogVisible.value = true
}

// 发布内容
const handlePublish = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要发布这篇内容吗？',
      '发布内容',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用发布内容API
    ElMessage.success('发布成功')
    loadContentList()
  } catch (error) {
    // 用户取消
  }
}

// 内容表单提交
const handleContentSubmit = async () => {
  if (!contentFormRef.value) return
  
  try {
    await contentFormRef.value.validate()
    submitting.value = true
    
    // 调用创建/更新内容API
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    contentDialogVisible.value = false
    loadContentList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!contentFormRef.value) return
  
  try {
    // 临时修改状态为草稿
    const originalStatus = contentForm.status
    contentForm.status = 'draft'
    
    await contentFormRef.value.validate()
    submitting.value = true
    
    // 调用保存草稿API
    ElMessage.success('草稿保存成功')
    contentDialogVisible.value = false
    loadContentList()
    
    // 恢复原状态
    contentForm.status = originalStatus
  } catch (error) {
    ElMessage.error('保存草稿失败')
  } finally {
    submitting.value = false
  }
}

// 封面上传前检查
const beforeCoverUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理封面上传
const handleCoverUpload = async (options: any) => {
  // 模拟上传
  setTimeout(() => {
    contentForm.coverImage = 'https://via.placeholder.com/400x300?text=封面图片'
    ElMessage.success('封面上传成功')
  }, 1000)
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 确认标签输入
const handleTagInputConfirm = () => {
  if (tagInputValue.value && !contentForm.tags.includes(tagInputValue.value)) {
    contentForm.tags.push(tagInputValue.value)
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 删除标签
const removeTag = (tag: string) => {
  const index = contentForm.tags.indexOf(tag)
  if (index > -1) {
    contentForm.tags.splice(index, 1)
  }
}

// 批量发布
const handleBatchPublish = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量发布选中的 ${selectedRows.value.length} 篇内容吗？`,
      '批量发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用批量发布API
    ElMessage.success('批量发布成功')
    loadContentList()
  } catch (error) {
    // 用户取消
  }
}

// 批量下线
const handleBatchOffline = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量下线选中的 ${selectedRows.value.length} 篇内容吗？`,
      '批量下线',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用批量下线API
    ElMessage.success('批量下线成功')
    loadContentList()
  } catch (error) {
    // 用户取消
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量删除选中的 ${selectedRows.value.length} 篇内容吗？删除后无法恢复！`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 调用批量删除API
    ElMessage.success('批量删除成功')
    loadContentList()
  } catch (error) {
    // 用户取消
  }
}

// 更多操作
const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'preview':
      ElMessage.info('预览功能开发中...')
      break
    case 'copy':
      ElMessage.info('复制功能开发中...')
      break
    case 'set-top':
      ElMessage.info('设置置顶功能开发中...')
      break
    case 'cancel-top':
      ElMessage.info('取消置顶功能开发中...')
      break
    case 'set-hot':
      ElMessage.info('设置热门功能开发中...')
      break
    case 'offline':
      ElMessage.info('下线内容功能开发中...')
      break
    case 'delete':
      ElMessage.info('删除内容功能开发中...')
      break
  }
}

onMounted(() => {
  loadContentList()
})
</script>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.content-info {
  .content-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
  }

  .content-summary {
    color: #606266;
    font-size: 14px;
    margin-bottom: 8px;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .content-meta {
    font-size: 12px;
    color: #909399;
  }
}

.text-muted {
  color: #909399;
}

.content-detail {
  .content-main {
    .content-title {
      margin-bottom: 16px;
      color: #303133;
    }

    .content-meta {
      margin-bottom: 16px;
      padding-bottom: 16px;
      border-bottom: 1px solid #EBEEF5;
    }

    .content-summary {
      margin-bottom: 20px;
      padding: 16px;
      background: #F5F7FA;
      border-radius: 4px;
      line-height: 1.6;
    }

    .content-body {
      line-height: 1.8;
      color: #303133;

      :deep(p) {
        margin-bottom: 16px;
      }

      :deep(img) {
        max-width: 100%;
        height: auto;
      }
    }
  }

  .no-cover {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;
    background: #F5F7FA;

    .el-icon {
      font-size: 48px;
      margin-bottom: 8px;
    }
  }

  .content-tags {
    line-height: 1.8;
  }
}

.editor-container {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  overflow: hidden;

  .el-textarea {
    :deep(.el-textarea__inner) {
      border: none;
      resize: vertical;
    }
  }
}

.cover-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: 0.2s;
    width: 200px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #409EFF;
    }
  }

  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
}

.tag-input {
  line-height: 1.8;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }

  .content-info {
    .content-title {
      font-size: 14px;
    }

    .content-summary {
      font-size: 12px;
    }
  }
}
</style>